{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# Numpy介绍\n",
    "- Numpy（NumericalPython）是一个开源的Python科学计算库，用于快速处理任意维度的数组。\n",
    "- Numpy支持常见的数组和矩阵操作。对于同样的数值计算任务，使用Numpy比直接使用Python要简洁的多。\n",
    "- Numpy使用ndarray对象来处理多维数组，该对象是一个快速而灵活的大数据容器。\n",
    "N - DIMENSIONALARRAYS(ndarray):n维数组\n"
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# NumPy的优势\n",
    "- 对于同样的数值计算任务，使用NumPy要比直接编写Python代码便捷得多；\n",
    "- NumPy中的数组的存储效率和输入输出性能均远远优于Python中等价的基本数据结构，且其能够提升的性能是 与数组中的\n",
    "元素成比例的；\n",
    "- NumPy的大部分代码都是用C语言写的，其底层算法在设计时就有着优异的性能，这使得NumPy比纯Python代 码高\n",
    "效得多"
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 4.1 列表如何转为ndarray"
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:24.483584Z",
     "start_time": "2025-01-16T15:13:24.389772Z"
    }
   },
   "source": [
    "#列表转ndarray\n",
    "import numpy as np\n",
    "\n",
    "list1 = [1, 2, 3, 4]\n",
    "print(list1)\n",
    "print(type(list1))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4]\n",
      "<class 'list'>\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:25.025787Z",
     "start_time": "2025-01-16T15:13:25.022188Z"
    }
   },
   "cell_type": "code",
   "source": [
    "oneArray = np.array(list1)\n",
    "print(oneArray)\n",
    "print(type(oneArray))  #类型是ndarray(无',')"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 4]\n",
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 4.2 ndarray与Python原生list运算效率对比"
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:32.650790Z",
     "start_time": "2025-01-16T15:13:25.040388Z"
    }
   },
   "source": [
    "import random\n",
    "import time\n",
    "import numpy as np\n",
    "\n",
    "#随机1亿个数据\n",
    "a = []\n",
    "for i in range(100000000):  # =10**8\n",
    "    a.append(random.random())\n",
    "print('随机完毕')"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "随机完毕\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:35.198558Z",
     "start_time": "2025-01-16T15:13:32.651800Z"
    }
   },
   "cell_type": "code",
   "source": [
    "b = np.array(a)  # 转换为ndarray\n",
    "print('转换完毕')"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "转换完毕\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:35.667362Z",
     "start_time": "2025-01-16T15:13:35.199069Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#ndarray的计算效率优于python的list\n",
    "t1 = time.time()\n",
    "sum1 = sum(a)\n",
    "t2 = time.time()\n",
    "\n",
    "t4 = time.time()\n",
    "sum3 = np.sum(b)\n",
    "t5 = time.time()\n",
    "print(t2 - t1, t5 - t4)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.3878297805786133 0.06655502319335938\n"
     ]
    }
   ],
   "execution_count": 6
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:35.672045Z",
     "start_time": "2025-01-16T15:13:35.668917Z"
    }
   },
   "source": [
    "t1 = np.array([1, 2, 3])\n",
    "print(t1)\n",
    "print(type(t1))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3]\n",
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.075794Z",
     "start_time": "2025-01-16T15:13:35.673050Z"
    }
   },
   "source": [
    "print(type(range(10)))  # range返回的是一个range对象，不能直接转换为ndarray\n",
    "t2 = np.array(range(10))\n",
    "print(t2)\n",
    "print(type(t2))  # 性能不如下面代码"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'range'>\n",
      "[0 1 2 3 4 5 6 7 8 9]\n",
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.091106Z",
     "start_time": "2025-01-16T15:13:36.076821Z"
    }
   },
   "source": [
    "t3 = np.arange(0, 10, 2)  # 等价于range(0,10,2),返回ndarray\n",
    "print(t3)\n",
    "print(type(t3))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 2 4 6 8]\n",
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.097136Z",
     "start_time": "2025-01-16T15:13:36.092112Z"
    }
   },
   "source": [
    "#二维列表转ndarray\n",
    "import numpy as np\n",
    "\n",
    "list2 = [[1, 2], [3, 4], [5, 6]]\n",
    "\n",
    "twoArray = np.array(list2)\n",
    "print(type(twoArray))\n",
    "print(twoArray)\n",
    "print(list2)  #列表的输出是有逗号的，ndarray的输出是没有逗号的"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'numpy.ndarray'>\n",
      "[[1 2]\n",
      " [3 4]\n",
      " [5 6]]\n",
      "[[1, 2], [3, 4], [5, 6]]\n"
     ]
    }
   ],
   "execution_count": 10
  },
  {
   "cell_type": "code",
   "source": "twoArray.tolist()  # ndarray转换为列表",
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.104160Z",
     "start_time": "2025-01-16T15:13:36.098137Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[1, 2], [3, 4], [5, 6]]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 11
  },
  {
   "cell_type": "markdown",
   "source": "## 4.3 常用属性",
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.109286Z",
     "start_time": "2025-01-16T15:13:36.104160Z"
    }
   },
   "source": [
    "#看ndarray的各种属性\n",
    "list2 = [[1, 2], [3, 4], [5, 6]]\n",
    "\n",
    "twoArray = np.array(list2)\n",
    "# 获取数组的维度( 注意： 与函数的参数很像) \n",
    "print(twoArray.ndim)\n",
    "# 形状（行，列） (0 axis,1 axis)\n",
    "print(twoArray.shape)\n",
    "# 有多少个元素\n",
    "print(twoArray.size)\n",
    "# 数据类型\n",
    "print(twoArray.dtype)  #默认int64，8个字节，-21亿^21亿-正的"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "(3, 2)\n",
      "6\n",
      "int64\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "cell_type": "markdown",
   "source": "## 4.4 调整数组的形状",
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.115356Z",
     "start_time": "2025-01-16T15:13:36.110294Z"
    }
   },
   "source": [
    "four = np.array([[1, 2, 3], [4, 5, 6]])\n",
    "print(four)\n",
    "# 修改的是原有的\n",
    "four1 = four\n",
    "print(id(four))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2 3]\n",
      " [4 5 6]]\n",
      "2436862275728\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.120835Z",
     "start_time": "2025-01-16T15:13:36.115356Z"
    }
   },
   "cell_type": "code",
   "source": [
    "four.shape = (3, 2)  # 改变形状\n",
    "print(id(four))  # 地址不变\n",
    "print(id(four1))  # 地址与four相同\n",
    "print(four)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2436862275728\n",
      "2436862275728\n",
      "[[1 2]\n",
      " [3 4]\n",
      " [5 6]]\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "cell_type": "code",
   "source": [
    "print('-' * 50)\n",
    "# 返回一个新的数组，reshape后id和之前的不一样\n",
    "four2 = four.reshape(2, 3)\n",
    "print(four)\n",
    "print(id(four))\n",
    "print(id(four2))  # 地址与four不同\n",
    "four2"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.127730Z",
     "start_time": "2025-01-16T15:13:36.120835Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--------------------------------------------------\n",
      "[[1 2]\n",
      " [3 4]\n",
      " [5 6]]\n",
      "2436862275728\n",
      "2436862276016\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[1, 2, 3],\n",
       "       [4, 5, 6]])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.132706Z",
     "start_time": "2025-01-16T15:13:36.128247Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 将多维变成一维数组(6,)!\n",
    "five = four.reshape((6,), order='C')\n",
    "# 默认情况下‘C’以行为主的顺序展开，‘F’（Fortran风格）意味着以列的顺序展开\n",
    "six = four.flatten()  # 展开成一维数组\n",
    "print(five)\n",
    "print('-' * 50)\n",
    "print(six)\n",
    "\n",
    "# print(five.reshape(3,2))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 4 5 6]\n",
      "--------------------------------------------------\n",
      "[1 2 3 4 5 6]\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.139272Z",
     "start_time": "2025-01-16T15:13:36.132706Z"
    }
   },
   "cell_type": "code",
   "source": [
    "seven = five.reshape(3, 2)  # 再变回去\n",
    "print(seven)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2]\n",
      " [3 4]\n",
      " [5 6]]\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "cell_type": "code",
   "source": [
    "print('-' * 50)\n",
    "# 拓展：数组的形状\n",
    "t = np.arange(24)  #和列表的range函数一样，生成一个数组\n",
    "print(t)\n",
    "print(f'shape{t.shape}')\n",
    "print(t.ndim)\n",
    "# 转换成二维\n",
    "t1 = t.reshape((4, 6))\n",
    "print(t1)\n",
    "print(t1.shape)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.144482Z",
     "start_time": "2025-01-16T15:13:36.139272Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--------------------------------------------------\n",
      "[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]\n",
      "shape(24,)\n",
      "1\n",
      "[[ 0  1  2  3  4  5]\n",
      " [ 6  7  8  9 10 11]\n",
      " [12 13 14 15 16 17]\n",
      " [18 19 20 21 22 23]]\n",
      "(4, 6)\n"
     ]
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.150414Z",
     "start_time": "2025-01-16T15:13:36.145511Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 转成三维\n",
    "#最前面的是零轴，轴越小，越靠外，最小的轴是最外层\n",
    "# 0轴，1轴，2轴\n",
    "t2 = t.reshape((2, 3, 4))\n",
    "print(t2)\n",
    "print(f'shape{t2.shape}')\n",
    "print(t2.ndim)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[ 0  1  2  3]\n",
      "  [ 4  5  6  7]\n",
      "  [ 8  9 10 11]]\n",
      "\n",
      " [[12 13 14 15]\n",
      "  [16 17 18 19]\n",
      "  [20 21 22 23]]]\n",
      "shape(2, 3, 4)\n",
      "3\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.155796Z",
     "start_time": "2025-01-16T15:13:36.151421Z"
    }
   },
   "cell_type": "code",
   "source": [
    "t3 = t.reshape((2, 3, 2, 2))\n",
    "print(t3)\n",
    "print(t3.shape)\n",
    "print(t3.ndim)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[[ 0  1]\n",
      "   [ 2  3]]\n",
      "\n",
      "  [[ 4  5]\n",
      "   [ 6  7]]\n",
      "\n",
      "  [[ 8  9]\n",
      "   [10 11]]]\n",
      "\n",
      "\n",
      " [[[12 13]\n",
      "   [14 15]]\n",
      "\n",
      "  [[16 17]\n",
      "   [18 19]]\n",
      "\n",
      "  [[20 21]\n",
      "   [22 23]]]]\n",
      "(2, 3, 2, 2)\n",
      "4\n"
     ]
    }
   ],
   "execution_count": 20
  },
  {
   "cell_type": "markdown",
   "source": "## 4.5 数组转换为列表",
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.696606Z",
     "start_time": "2025-01-16T15:13:36.155796Z"
    }
   },
   "source": [
    "#将数组转换为列表 tolist\n",
    "a = np.array([9, 12, 88, 14, 25])\n",
    "print(type(a))\n",
    "list_a = a.tolist()\n",
    "print(list_a)\n",
    "print(type(list_a))\n"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'numpy.ndarray'>\n",
      "[9, 12, 88, 14, 25]\n",
      "<class 'list'>\n"
     ]
    }
   ],
   "execution_count": 21
  },
  {
   "cell_type": "markdown",
   "source": [
    "# 5 NumPy的数据类型"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.701693Z",
     "start_time": "2025-01-16T15:13:36.697112Z"
    }
   },
   "source": [
    "import random\n",
    "\n",
    "f = np.array([1, 2, 3, 4, 127], dtype=np.int16)  # 返回数组中每个元素的字节单位长度,dtype设置数据类型\n",
    "print(f.itemsize)  # 2 np.int16(2个字节)\n",
    "# 获取数据类型\n",
    "print(f.dtype)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "int16\n"
     ]
    }
   ],
   "execution_count": 22
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.709029Z",
     "start_time": "2025-01-16T15:13:36.702701Z"
    }
   },
   "cell_type": "code",
   "source": [
    "f = np.array([1, 2, 3, 4, 127], dtype=np.int8)  # 每个元素1字节，-128~127\n",
    "f[4] = f[4] + 1  #溢出\n",
    "f[4]  # -128"
   ],
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Administrator\\AppData\\Local\\Temp\\ipykernel_28052\\2714406640.py:2: RuntimeWarning: overflow encountered in scalar add\n",
      "  f[4] = f[4] + 1  #溢出\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "np.int8(-128)"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 23
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.713726Z",
     "start_time": "2025-01-16T15:13:36.709029Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 调整数据类型\n",
    "f1 = f.astype(np.int64)\n",
    "print(f1.dtype)\n",
    "print(f1.itemsize)  #显示字节数"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "int64\n",
      "8\n"
     ]
    }
   ],
   "execution_count": 24
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.719770Z",
     "start_time": "2025-01-16T15:13:36.714736Z"
    }
   },
   "cell_type": "code",
   "source": "random.random()  # 随机生成0-1之间的小数，想更大乘1个系数即可",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.6229080827678585"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 25
  },
  {
   "cell_type": "code",
   "source": [
    "# 拓展随机生成小数\n",
    "print(round(random.random(), 2))  # 保留两位小数\n",
    "# np.float16 半精度\n",
    "arr = np.array([random.random() for i in range(10)])\n",
    "print(arr)\n",
    "print(arr.itemsize)\n",
    "print(arr.dtype)\n",
    "# 取小数点后两位\n",
    "print(np.round(arr, 2))  # 保留两位小数，上取整"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.725371Z",
     "start_time": "2025-01-16T15:13:36.719770Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.76\n",
      "[0.26174637 0.13312098 0.60243842 0.562301   0.34243131 0.53185928\n",
      " 0.35630161 0.05078528 0.23259502 0.92021483]\n",
      "8\n",
      "float64\n",
      "[0.26 0.13 0.6  0.56 0.34 0.53 0.36 0.05 0.23 0.92]\n"
     ]
    }
   ],
   "execution_count": 26
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 5.1 数组和数的计算"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.730920Z",
     "start_time": "2025-01-16T15:13:36.725371Z"
    }
   },
   "cell_type": "code",
   "source": "# [1,2,3]+5  # 列表不能直接加整数，ndarry可以",
   "outputs": [],
   "execution_count": 27
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.737440Z",
     "start_time": "2025-01-16T15:13:36.731935Z"
    }
   },
   "source": [
    "# 由于numpy的广播机机制在运算过程中，加减乘除的值被广播到所有的元素上面\n",
    "t1 = np.arange(24).reshape((6, 4))\n",
    "print(t1)\n",
    "print(\"-\" * 20)\n",
    "t2 = t1.tolist()\n",
    "print(t1 + 2)\n",
    "# print(t2+2) 不能对列表进行直接加整数操作\n",
    "print(\"-\" * 20)\n",
    "print(t1 * 2)\n",
    "print(\"-\" * 20)\n",
    "print(t1 / 2)\n",
    "\n",
    "#无论多少维的ndarray都可以直接和一个常数进行运算"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  1  2  3]\n",
      " [ 4  5  6  7]\n",
      " [ 8  9 10 11]\n",
      " [12 13 14 15]\n",
      " [16 17 18 19]\n",
      " [20 21 22 23]]\n",
      "--------------------\n",
      "[[ 2  3  4  5]\n",
      " [ 6  7  8  9]\n",
      " [10 11 12 13]\n",
      " [14 15 16 17]\n",
      " [18 19 20 21]\n",
      " [22 23 24 25]]\n",
      "--------------------\n",
      "[[ 0  2  4  6]\n",
      " [ 8 10 12 14]\n",
      " [16 18 20 22]\n",
      " [24 26 28 30]\n",
      " [32 34 36 38]\n",
      " [40 42 44 46]]\n",
      "--------------------\n",
      "[[ 0.   0.5  1.   1.5]\n",
      " [ 2.   2.5  3.   3.5]\n",
      " [ 4.   4.5  5.   5.5]\n",
      " [ 6.   6.5  7.   7.5]\n",
      " [ 8.   8.5  9.   9.5]\n",
      " [10.  10.5 11.  11.5]]\n"
     ]
    }
   ],
   "execution_count": 28
  },
  {
   "cell_type": "markdown",
   "source": "## 5.2 ndarray与ndarray的运算",
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.743396Z",
     "start_time": "2025-01-16T15:13:36.738464Z"
    }
   },
   "source": [
    "#形状相同,才可以进行加减乘除\n",
    "t1 = np.arange(24).reshape((6, 4))\n",
    "t2 = np.arange(100, 124).reshape((6, 4))\n",
    "print(t1)\n",
    "print(t2)\n",
    "print('-' * 50)\n",
    "print(t1 + t2)\n",
    "print('-' * 50)\n",
    "print(t1 * t2)  #是否是矩阵乘法？不是\n"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  1  2  3]\n",
      " [ 4  5  6  7]\n",
      " [ 8  9 10 11]\n",
      " [12 13 14 15]\n",
      " [16 17 18 19]\n",
      " [20 21 22 23]]\n",
      "[[100 101 102 103]\n",
      " [104 105 106 107]\n",
      " [108 109 110 111]\n",
      " [112 113 114 115]\n",
      " [116 117 118 119]\n",
      " [120 121 122 123]]\n",
      "--------------------------------------------------\n",
      "[[100 102 104 106]\n",
      " [108 110 112 114]\n",
      " [116 118 120 122]\n",
      " [124 126 128 130]\n",
      " [132 134 136 138]\n",
      " [140 142 144 146]]\n",
      "--------------------------------------------------\n",
      "[[   0  101  204  309]\n",
      " [ 416  525  636  749]\n",
      " [ 864  981 1100 1221]\n",
      " [1344 1469 1596 1725]\n",
      " [1856 1989 2124 2261]\n",
      " [2400 2541 2684 2829]]\n"
     ]
    }
   ],
   "execution_count": 29
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.749471Z",
     "start_time": "2025-01-16T15:13:36.744403Z"
    }
   },
   "source": [
    "#shape不同，不能进行运算\n",
    "t1 = np.arange(24).reshape((4, 6))\n",
    "t2 = np.arange(6).reshape((1, 6))  # 有一个维度不同，但有维度为1可以分别运算\n",
    "print(t1)\n",
    "print(t2)\n",
    "print('-' * 50)\n",
    "print(t1 - t2)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  1  2  3  4  5]\n",
      " [ 6  7  8  9 10 11]\n",
      " [12 13 14 15 16 17]\n",
      " [18 19 20 21 22 23]]\n",
      "[[0 1 2 3 4 5]]\n",
      "--------------------------------------------------\n",
      "[[ 0  0  0  0  0  0]\n",
      " [ 6  6  6  6  6  6]\n",
      " [12 12 12 12 12 12]\n",
      " [18 18 18 18 18 18]]\n"
     ]
    }
   ],
   "execution_count": 30
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.756315Z",
     "start_time": "2025-01-16T15:13:36.751810Z"
    }
   },
   "source": [
    "#一维数组和二维数组进行运算时，一维的元素个数和列数相等\n",
    "t1 = np.arange(24).reshape((4, 6))\n",
    "t2 = np.arange(6).reshape((1, 6))\n",
    "print(t2.shape)\n",
    "print(t1)\n",
    "print(t2)\n",
    "t1 - t2"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1, 6)\n",
      "[[ 0  1  2  3  4  5]\n",
      " [ 6  7  8  9 10 11]\n",
      " [12 13 14 15 16 17]\n",
      " [18 19 20 21 22 23]]\n",
      "[[0 1 2 3 4 5]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[ 0,  0,  0,  0,  0,  0],\n",
       "       [ 6,  6,  6,  6,  6,  6],\n",
       "       [12, 12, 12, 12, 12, 12],\n",
       "       [18, 18, 18, 18, 18, 18]])"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 31
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.761626Z",
     "start_time": "2025-01-16T15:13:36.756827Z"
    }
   },
   "cell_type": "code",
   "source": "(t1 - t2).shape",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(4, 6)"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 32
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.768939Z",
     "start_time": "2025-01-16T15:13:36.762634Z"
    }
   },
   "source": [
    "t1 = np.arange(24).reshape((4, 6))\n",
    "t2 = np.arange(4).reshape((4, 1))\n",
    "print(t1)\n",
    "print(t2)\n",
    "t1 - t2"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  1  2  3  4  5]\n",
      " [ 6  7  8  9 10 11]\n",
      " [12 13 14 15 16 17]\n",
      " [18 19 20 21 22 23]]\n",
      "[[0]\n",
      " [1]\n",
      " [2]\n",
      " [3]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[ 0,  1,  2,  3,  4,  5],\n",
       "       [ 5,  6,  7,  8,  9, 10],\n",
       "       [10, 11, 12, 13, 14, 15],\n",
       "       [15, 16, 17, 18, 19, 20]])"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 33
  },
  {
   "cell_type": "code",
   "source": [
    "#随机3维数组\n",
    "a = np.arange(24).reshape((2, 3, 4))\n",
    "b = np.arange(12).reshape((1, 3, 4))\n",
    "print(a)\n",
    "print('-' * 50)\n",
    "print(b)\n",
    "print('-' * 50)\n",
    "a - b"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.807875Z",
     "start_time": "2025-01-16T15:13:36.768939Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[ 0  1  2  3]\n",
      "  [ 4  5  6  7]\n",
      "  [ 8  9 10 11]]\n",
      "\n",
      " [[12 13 14 15]\n",
      "  [16 17 18 19]\n",
      "  [20 21 22 23]]]\n",
      "--------------------------------------------------\n",
      "[[[ 0  1  2  3]\n",
      "  [ 4  5  6  7]\n",
      "  [ 8  9 10 11]]]\n",
      "--------------------------------------------------\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[[ 0,  0,  0,  0],\n",
       "        [ 0,  0,  0,  0],\n",
       "        [ 0,  0,  0,  0]],\n",
       "\n",
       "       [[12, 12, 12, 12],\n",
       "        [12, 12, 12, 12],\n",
       "        [12, 12, 12, 12]]])"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 34
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "结论：ndim要相同，可以某一个轴的size不同，但是其中一个ndarray必须对应的轴的size为1"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 练习轴"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.813606Z",
     "start_time": "2025-01-16T15:13:36.808953Z"
    }
   },
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([[1, 2, 3], [4, 5, 6]])\n",
    "print(a)\n",
    "print(\"-\" * 20)\n",
    "print(np.sum(a, axis=0))  # [5 7 9]，列和\n",
    "print(\"-\" * 20)\n",
    "print(np.sum(a, axis=1))  # [ 6 15] 行和\n",
    "print(\"-\" * 20)\n",
    "print(np.sum(a))\n",
    "print(\"-\" * 20)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2 3]\n",
      " [4 5 6]]\n",
      "--------------------\n",
      "[5 7 9]\n",
      "--------------------\n",
      "[ 6 15]\n",
      "--------------------\n",
      "21\n",
      "--------------------\n"
     ]
    }
   ],
   "execution_count": 35
  },
  {
   "cell_type": "code",
   "source": [
    "a = np.arange(24).reshape((2, 3, 4))\n",
    "b = np.sum(a, axis=0)  # 维度1的和\n",
    "print(b.shape)\n",
    "print(b)\n",
    "c = np.sum(a, axis=1)  # 维度2的和\n",
    "print(\"-\" * 20)\n",
    "print(c.shape)\n",
    "d = np.sum(a, axis=2)  # 维度3的和\n",
    "print(\"-\" * 20)\n",
    "print(d.shape)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.819300Z",
     "start_time": "2025-01-16T15:13:36.814616Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3, 4)\n",
      "[[12 14 16 18]\n",
      " [20 22 24 26]\n",
      " [28 30 32 34]]\n",
      "--------------------\n",
      "(2, 4)\n",
      "--------------------\n",
      "(2, 3)\n"
     ]
    }
   ],
   "execution_count": 36
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 索引和切片"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.825522Z",
     "start_time": "2025-01-16T15:13:36.820306Z"
    }
   },
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.arange(10)\n",
    "# 冒号分隔切片参数 start:stop:step 来进行切片操作print(a[2:7:2])# 从索引2开始到索引7停止，间隔为2\n",
    "# 如果只放置一个参数，如 [2]，将返回与该索引相对应的单个元素\n",
    "print(a[0], a)\n",
    "\n",
    "# 如果为 [2:]，表示从该索引开始以后的所有项都将被提取\n",
    "print(a[2:])\n",
    "\n",
    "print(a[2:8:2])  #切片是左闭右开\n"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 [0 1 2 3 4 5 6 7 8 9]\n",
      "[2 3 4 5 6 7 8 9]\n",
      "[2 4 6]\n"
     ]
    }
   ],
   "execution_count": 37
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.831405Z",
     "start_time": "2025-01-16T15:13:36.825522Z"
    }
   },
   "source": [
    "import numpy as np\n",
    "\n",
    "t1 = np.arange(24).reshape(4, 6)\n",
    "print(f't1:{t1}')\n",
    "print('*' * 20)\n",
    "print(f't1[1]:{t1[1]}')  # 取一行(一行代表是一条数据，索引也是从0开始的) \n",
    "# print(t1[1,:]) # 取一行\n",
    "print('*' * 20)\n",
    "print(f't1[1:]:{t1[1:]}')  # 取连续的多行\n",
    "print('*' * 20)\n",
    "print(f't1[1:3, :]:{t1[1:3, :]}')  # 取连续的多行 print(f't1[1:3]:{t1[1:3]}')\n",
    "print('*' * 20)\n",
    "print(t1[[0, 2, 3]])  # 取不连续的多行\n",
    "print('*' * 20)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "t1:[[ 0  1  2  3  4  5]\n",
      " [ 6  7  8  9 10 11]\n",
      " [12 13 14 15 16 17]\n",
      " [18 19 20 21 22 23]]\n",
      "********************\n",
      "t1[1]:[ 6  7  8  9 10 11]\n",
      "********************\n",
      "t1[1:]:[[ 6  7  8  9 10 11]\n",
      " [12 13 14 15 16 17]\n",
      " [18 19 20 21 22 23]]\n",
      "********************\n",
      "t1[1:3, :]:[[ 6  7  8  9 10 11]\n",
      " [12 13 14 15 16 17]]\n",
      "********************\n",
      "[[ 0  1  2  3  4  5]\n",
      " [12 13 14 15 16 17]\n",
      " [18 19 20 21 22 23]]\n",
      "********************\n"
     ]
    }
   ],
   "execution_count": 38
  },
  {
   "cell_type": "code",
   "source": [
    "#看列表,列表不支持取不连续的行\n",
    "t2 = np.arange(24).reshape(4, 6).tolist()\n",
    "t2[[0, 2, 3]]  # typeError"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.863436Z",
     "start_time": "2025-01-16T15:13:36.832435Z"
    }
   },
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "list indices must be integers or slices, not list",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mTypeError\u001B[0m                                 Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[39], line 3\u001B[0m\n\u001B[0;32m      1\u001B[0m \u001B[38;5;66;03m#看列表,列表不支持取不连续的行\u001B[39;00m\n\u001B[0;32m      2\u001B[0m t2 \u001B[38;5;241m=\u001B[39m np\u001B[38;5;241m.\u001B[39marange(\u001B[38;5;241m24\u001B[39m)\u001B[38;5;241m.\u001B[39mreshape(\u001B[38;5;241m4\u001B[39m, \u001B[38;5;241m6\u001B[39m)\u001B[38;5;241m.\u001B[39mtolist()\n\u001B[1;32m----> 3\u001B[0m \u001B[43mt2\u001B[49m\u001B[43m[\u001B[49m\u001B[43m[\u001B[49m\u001B[38;5;241;43m0\u001B[39;49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;241;43m2\u001B[39;49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;241;43m3\u001B[39;49m\u001B[43m]\u001B[49m\u001B[43m]\u001B[49m  \u001B[38;5;66;03m# typeError\u001B[39;00m\n",
      "\u001B[1;31mTypeError\u001B[0m: list indices must be integers or slices, not list"
     ]
    }
   ],
   "execution_count": 39
  },
  {
   "cell_type": "code",
   "source": [
    "print(f't1:{t1}')\n",
    "print('*' * 20)\n",
    "print(f't1[:, 1]:{t1[:, 1]}')  # 取一列\n",
    "print('*' * 20)\n",
    "print(f't1[:, 1:]:{t1[:, 1:]}')  # 连续的多列\n",
    "print('*' * 20)\n",
    "print(f't1[:, [0, 2, 3]]:{t1[:, [0, 2, 3]]}')  # 取不连续的多列\n",
    "print('*' * 20)\n",
    "print(t1[2, 3])  # # 取某一个值,三行四列  py是t1[2][3]\n",
    "print('*' * 20)\n",
    "print(t1[[0, 1, 1], [0, 1, 3]])  # 取多个不连续的值，[[行，行。。。],[列，列。。。]]\n",
    "\n",
    "t1[1:3, 1:4]  #取1-3行，1-4列"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 修改值"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "\n",
    "t = np.arange(24).reshape(4, 6)\n",
    "print(t)\n",
    "print(id(t))\n",
    "print('-' * 50)\n",
    "# # 修改某一行的值\n",
    "# t[1,:]=0\n",
    "#\n",
    "# # 修改某一列的值\n",
    "# t[:,1]=0\n",
    "#\n",
    "# # 修改连续多行\n",
    "# t[1:3,:]=0\n",
    "#\n",
    "# # 修改连续多列\n",
    "# t[:,1:4]=0\n",
    "#\n",
    "# # 修改多行多列，取第二行到第四行，第三列到第五列\n",
    "# t[1:3,2:5]=0\n",
    "#\n",
    "# # 修改多个不相邻的点\n",
    "# t[[0,1],[1,3]]=0\n",
    "\n",
    "# 可以根据条件修改，比如讲小于10的值改掉\n",
    "# t[t<10]=0\n",
    "\n",
    "# 使用逻辑判断\n",
    "# np.logical_and\t& # np.logical_or\t|\n",
    "# np.logical_not\t\t~\n",
    "# t[(t>2)&(t<6)]=0\t# 逻辑与，and\n",
    "# t[(t<2)|(t>6)]=0\t# 逻辑或，or\n",
    "# t[~(t>6)]=0\t# 逻辑非,<=6的改为0\n",
    "# print(t)\n",
    "t = t.clip(10, 18)  # 限制数组的最小值和最大值，小于10的改为10，大于18的改为18\n",
    "print(id(t))\n",
    "t\n"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "t = np.arange(24).reshape(4, 6)\n",
    "t < 10"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.865448Z",
     "start_time": "2025-01-16T15:13:36.865448Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#python的三目运算\n",
    "a = 10\n",
    "b = 15\n",
    "c = a if a > b else b  # 等于较大的\n",
    "c"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": [
    "# 拓 展\n",
    "# 三目运算（ np.where(condition, x, y)满足条件(condition)，输出x，不满足输出y。)）\n",
    "score = np.array([[80, 88], [82, 81], [75, 81]])\n",
    "print(score)\n",
    "result = np.where(score < 80, True, False)  #类似于if else\n",
    "print(result)"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.867956Z",
     "start_time": "2025-01-16T15:13:36.867956Z"
    }
   },
   "cell_type": "code",
   "source": [
    "score[result] = 100  # True的改为100\n",
    "score"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 数据的添加，删除与去重"
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "#### 1. numpy.append 函数在数组的末尾添加值。 追加操作会分配整个数组，并把原来的数组复制到新数组中。\n",
    "此外，输入数组的维度必须匹配否则将生成ValueError。\n",
    "\n",
    "参 数 说 明 :                                                                                               \n",
    "arr：输入数组                                                                                           \n",
    "values：要向arr添加的值，需要和arr形状相同（除了要添加的轴）                                                       \n",
    "axis：默认为None。当axis无定义时，是横向加成，返回总是为一维数组！当axis有定义的时候，分别为0和1的时候（列数要相同）。当axis为1时，数组是加在右边（行数要相同）。"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([[1, 2, 3], [4, 5, 6]])\n",
    "\n",
    "print('第一个数组：')\n",
    "print(a)\n",
    "\n",
    "print(' 向数组添加元素 ：')\n",
    "print(np.append(a, [7, 8, 9]))  #ndarray会被展平\n",
    "print('-' * 50)\n",
    "print(a)  # a没有被修改"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.868976Z",
     "start_time": "2025-01-16T15:13:36.868976Z"
    }
   },
   "cell_type": "code",
   "source": [
    "b = np.array([[7, 8, 9]])\n",
    "print(b.ndim)\n",
    "print(b)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": [
    "print('沿轴0添加元素：')  #往哪个轴添加，那个轴size就变大\n",
    "print(np.append(a, [[7, 8, 9]], axis=0))\n",
    "print('-' * 50)\n",
    "\n",
    "print('沿轴1添加元素：')\n",
    "print(np.append(a, [[5, 5, 5], [7, 8, 9]], axis=1))"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "#### 2. numpy.insert\n",
    "- 函数在给定索引之前，沿给定轴在输入数组中插入值。\n",
    "- 如果值的类型转换为要插入，则它与输入数组不同。\n",
    "- 插入没有原地的，函数会返回一个新数组。 此外，如果未提供轴，则输入数组会被展开。"
   ]
  },
  {
   "cell_type": "code",
   "source": [
    "a = np.array([[1, 2], [3, 4], [5, 6]])\n",
    "\n",
    "print('第一个数组a：')\n",
    "print(a)\n",
    "\n",
    "print('未传递 Axis 参数。在插入之前输入数组会被展开。')\n",
    "print(np.insert(a, 1, [11, 22]))\n",
    "print('-' * 50)\n",
    "print('沿轴0插入：')\n",
    "print(np.insert(a, 1, [11, 12], axis=0))  #哪个轴插入，哪个轴size变大\n",
    "# print('传递了 Axis 参数。 会广播值数组来配输入数组。')\n",
    "\n",
    "print('沿轴0广播：')\n",
    "print(np.insert(a, 1, 11, axis=0))\n",
    "print('\\n')\n",
    "\n",
    "print('沿轴1广播：')\n",
    "print(np.insert(a, 1, [1, 2, 5], axis=1))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.871159Z",
     "start_time": "2025-01-16T15:13:36.871159Z"
    }
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "#### numpy.delete 函数返回从输入数组中删除指定子数组的新数组。 与 insert() 函数的情况一样，\n",
    "如果未提供轴参数， 则输入数组将展开。\n",
    "\n",
    "参数说明 ： \n",
    "- arr：输入数组\n",
    "- obj：可以被切片，整数或者整数数组，表明要从输入数组删除的子数组axis：\n",
    "- 沿着它删除给定子数组的轴，如果未提供，则输入数组会被展开"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.871159Z",
     "start_time": "2025-01-16T15:13:36.871159Z"
    }
   },
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.arange(12).reshape(3, 4)\n",
    "print('数组a：')\n",
    "print(a)\n",
    "\n",
    "print('未传递 Axis 参数。在删除5之前输入数组会被展开。')\n",
    "print(np.delete(a, 5))\n",
    "print('-' * 50)\n",
    "print(a)  # a没有被修改\n",
    "\n",
    "print('删除第一行：')\n",
    "print(np.delete(a, 1, axis=0))\n",
    "print('-' * 50)\n",
    "\n",
    "print('删除第一列：')\n",
    "print(np.delete(a, 1, axis=1))"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "#### numpy.unique 函数用于去除数组中的重复元素。\n",
    "参数说明：\n",
    "- arr：输入数组，如果不是一维数组则会展平\n",
    "- return_index：如果为true，返回新列表元素在旧列表中的位置（下标），并以列表形式储\n",
    "- return_inverse：如果为true，返回旧列表元素在新列表中的位置（下标），并以列表形式储\n",
    "- return_counts：如果为true，返回去重数组中的元素在原数组中的出现次数\n"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.872159Z",
     "start_time": "2025-01-16T15:13:36.872159Z"
    }
   },
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([5, 2, 6, 2, 7, 5, 6, 9, 8, 2])\n",
    "\n",
    "print('第一个数组a：')\n",
    "print(a)\n",
    "print('-' * 50)\n",
    "\n",
    "# 去除重复元素，输出的是有序序列\n",
    "print('a的去重值：')\n",
    "u = np.unique(a)\n",
    "print(u)\n",
    "print('-' * 50)\n",
    "\n",
    "print('去重数组的索引数组：')\n",
    "u, indices = np.unique(a, return_index=True)\n",
    "print(u)\n",
    "print(indices)\n",
    "print('-' * 50)\n",
    "\n",
    "print('我们可以看到每个和原数组下标对应的数值：')\n",
    "print('去重数组的下标：')\n",
    "u, indices = np.unique(a, return_inverse=True)\n",
    "print(u)\n",
    "print(indices)\n",
    "print('-' * 50)\n",
    "\n",
    "print('返回去重元素的重复数量：')\n",
    "u, indices = np.unique(a, return_counts=True)\n",
    "print(u)\n",
    "print(indices)\n",
    "u"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# numpy的数学计算\n",
    "通用函数：\n",
    "- numpy.sqrt(array)\t平方根函数\n",
    "- numpy.exp(array)\te^array[i]的数组\n",
    "- numpy.abs/fabs(array)\t计算绝对值\n",
    "- numpy.square(array)\t计算各元素的平方 等于array\t2\n",
    "- numpy.log/log10/log2(array)\t计算各元素的各种对数\n",
    "- numpy.sign(array)\t计算各元素正负号\n",
    "- numpy.isnan(array)\t计算各元素是否为NaN\n",
    "- numpy.isinf(array)\t计算各元素是否为NaN\n",
    "- numpy.cos/cosh/sin/sinh/tan/tanh(array) 三角函数\n",
    "- numpy.modf(array)\t将array中值得整数和小数分离，作两个数组返回\n",
    "- numpy.ceil(array)\t向上取整,也就是取比这个数大的整数\n",
    "- numpy.floor(array)\t向下取整,也就是取比这个数小的整数\n",
    "- numpy.rint(array)\t四舍五入\n",
    "- numpy.trunc(array)\t向0取整\n",
    "- numpy.cos(array)\t正弦值\n",
    "- numpy.sin(array)\t余弦值\n",
    "- numpy.tan(array)\t正切值\n",
    "- numpy.add(array1,array2)\t元素级加法\n",
    "- numpy.subtract(array1,array2)\t元素级减法\n",
    "- numpy.multiply(array1,array2)\t元素级乘法\n",
    "- numpy.divide(array1,array2)\t元素级除法 array1./array2\n",
    "- numpy.power(array1,array2)\t元素级指数 array1.^array2\n",
    "- numpy.maximum/minimum(array1,aray2) 元素级最大值\n",
    "- numpy.fmax/fmin(array1,array2)\t元素级最大值，忽略NaN\n",
    "- numpy.mod(array1,array2)\t元素级求模\n",
    "- numpy.copysign(array1,array2)\t将第二个数组中值得符号复制给第一个数组中值\n",
    "- numpy.greater/greater_equal/less/less_equal/equal/not_equal (array1,array2) 元素级比较运算，产生布尔数组\n",
    "- numpy.logical_end/logical_or/logic_xor(array1,array2)元素级的真值逻辑运算\n"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "\n",
    "score = np.array([[80, 88], [82, 81], [75, 81]])\n",
    "print(score)\n",
    "# 1. 获取所有数据最大值\n",
    "result = np.max(score)\n",
    "print('max ', result)\n",
    "# 2. 获取某一个轴上的数据最大值，对应的轴就消失\n",
    "result = np.max(score, axis=1)\n",
    "print('axis=1 max ', result)\n",
    "# 3. 获取最小值\n",
    "result = np.min(score)\n",
    "print('min ', result)\n",
    "# 4. 获取某一个轴上的数据最小值\n",
    "result = np.min(score, axis=0)\n",
    "print('axis=0 min ', result)\n",
    "# 5. 数据的比较\n",
    "result = np.maximum([-2, -1, 0, 1, 2], 0)  # 第一个参数中的每一个数与第二个参数比较返回大的\n",
    "print(result)\n",
    "result = np.minimum([-2, -1, 0, 1, 2], 0)  # 第一个参数中的每一个数与第二个参数比较返回小的\n",
    "print(result)\n",
    "result = np.maximum([-2, -1, 4, 1, 2], [1, 2, 3, 4, 5])  # 接受的两个参数，也可以大小一致;第二个参数只是一个单独的值时，其实是用到了维度的广播机制；\n",
    "print(result)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": [
    "# 6. 求平均值\n",
    "result = np.mean(score)  # 获取所有数据的平均值\n",
    "print(result)\n",
    "result = np.mean(score, axis=0)  # 获取某一行或者某一列的平均值\n",
    "print(result)\n",
    "# 7. 求前缀和\n",
    "arr = np.array([[1, 2, 3], [4, 5, 6]])\n",
    "print(arr)\n",
    "print('-' * 50)\n",
    "print(arr.cumsum(axis=0))\n",
    "print(arr.cumsum(axis=1))\n",
    "# 拓展：方差var, 协方差cov, 计算平均值 average, 计算中位数 median"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": [
    "# 8. argmin求最小值索引\n",
    "print(score)\n",
    "print('-' * 50)\n",
    "result = np.argmin(score, axis=0)\n",
    "res = np.min(score, axis=0)  #这样我们就可以知道最小的81是第二排的，是从前往后遍历的\n",
    "print(result)\n",
    "print('-' * 50)\n",
    "print(res)\n",
    "print('\\n')\n",
    "# 9. 求每一列的标准差（这里是总体标准差）\n",
    "# 标准差是一组数据平均值分散程度的一种度量。一个较大的标准差，代表大部分数值和其平均值之间差异较大；\n",
    "# 一个较小的标准差，代表这些数据较接近平均值反应出数据的波动稳定情况，越大表示波动越大，越不稳定。\n",
    "result = np.std(score, axis=0)\n",
    "print(result)\n",
    "\n",
    "# 10. 极值\n",
    "result = np.ptp(score, axis=None)  #就是最大值和最小值的差\n",
    "print(result)"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "t = np.arange(30).reshape(10, 3)\n",
    "np.mean(t, axis=0)  # 轴0垂直向下"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 数组的拼接"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:36.875159Z",
     "start_time": "2025-01-16T15:13:36.875159Z"
    }
   },
   "source": [
    "# 有的时候我们需要将两个数据加起来一起研究分析，我们就可以将其进行拼接然后分析\n",
    "import numpy as np\n",
    "\n",
    "# 1. 根据轴连接的数组序列，concatenate没有改变数组的维度\n",
    "a = np.array([[1, 2], [3, 4]])\n",
    "b = np.array([[5, 6], [7, 8]])\n",
    "c = np.array([[9, 10], [11, 12]])\n",
    "\n",
    "# 要求a,b两个数组的维度相同\n",
    "print('沿轴0连接2个数组：')\n",
    "print(np.concatenate((a, b), axis=0))  #写哪个轴，哪个轴就变化\n",
    "print('-' * 50)\n",
    "print('沿轴1连接3个数组：')\n",
    "print(np.concatenate((a, b, c), axis=1))"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "#堆叠\n",
    "print(np.stack((a, b, c), axis=1).shape)  #stack会增加维度\n",
    "print(np.stack((a, b, c), axis=0).shape)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": [
    "# 2. 根据轴进行堆叠，2维会变为3维\n",
    "arrays = [np.arange(12).reshape(3, 4) for _ in range(10)]\n",
    "# print(arrays)\n",
    "print(len(arrays))\n",
    "print('沿轴 0 连接两个数组：')\n",
    "result0 = np.stack(arrays, axis=0)\n",
    "print(result0.shape)  #(10,3,4)\n",
    "# print (result0)"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": [
    "print(arrays[0])\n",
    "print('沿轴 1 连接两个数组：')\n",
    "result1 = np.stack(arrays, axis=1)\n",
    "print(result1.shape)  #(3,10,4)\n",
    "# print(result1)"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": [
    "result2 = np.stack(arrays, axis=-1)  # -1是最大的轴\n",
    "print(arrays[0])\n",
    "print('沿轴2连接两个数组：这里-1和2是等价的')\n",
    "print(result2.shape)\n",
    "# print(result2)"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": [
    "# 3. 矩阵垂直拼接，vstack没有增加维数，类似于concatenate   ---vertical\n",
    "v1 = [[0, 1, 2, 3, 4, 5],\n",
    "      [6, 7, 8, 9, 10, 11]]\n",
    "v2 = [[12, 13, 14, 15, 16, 17],\n",
    "      [18, 19, 20, 21, 22, 23]]\n",
    "result = np.vstack((v1, v2))\n",
    "print(result)\n",
    "\n",
    "# 4. 矩阵水平拼接，类似于concatenate  horizontal\n",
    "v1 = [[0, 1, 2, 3, 4, 5],\n",
    "      [6, 7, 8, 9, 10, 11]]\n",
    "v2 = [[12, 13, 14, 15, 16, 17],\n",
    "      [18, 19, 20, 21, 22, 23]]\n",
    "result = np.hstack((v1, v2))\n",
    "print(result)"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 分割\n",
    "\n",
    "参数说明：\n",
    "- ary：被分割的数组\n",
    "- indices_or_sections：是一个整数，就用该数平均切分，如果是一个数组，为沿轴切分的位置（左开右闭）\n",
    "- axis：沿着哪个维度进行切向，默认为0，横向切分。为1时，纵向切分\n"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "\n",
    "# 1. 将一个数组分割为多个子数组\n",
    "arr = np.arange(12).reshape(4, 3)\n",
    "print(arr)\n",
    "print('将数组分为三个大小相等的子数组：b是一个列表')\n",
    "b = np.split(arr, 3, axis=1)  #按那个轴，那个轴发生变化\n",
    "print(b)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "b[0].shape",
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": [
    "b = np.split(arr, 4, axis=0)\n",
    "print(b)"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": [
    "c = np.hsplit(arr, 3)\n",
    "print(c)  #c是列表\n",
    "print(c[0].shape)"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": [
    "d = np.random.random((2, 6))  # 不要用randmo.rand()\n",
    "print(d)"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": [
    "# # 2.numpy.hsplit 函数用于水平分割数组，通过指定要返回的相同形状的数组数量来拆分原数组。\n",
    "harr = np.floor(10 * np.random.random((2, 6)))\n",
    "print('原array：')\n",
    "print(harr)"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": [
    "# # 3.numpy.vsplit 沿着垂直轴分割\n",
    "a = np.arange(16).reshape(4, 4)\n",
    "\n",
    "print('第一个数组a：')\n",
    "print(a)\n",
    "print('-' * 50)\n",
    "\n",
    "print('竖直分割：')\n",
    "b = np.vsplit(a, 2)  # 2是分割的份数\n",
    "print(b)"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# numpy inf和nan\n",
    "\n",
    "C语言中表示最大的正整数值是0x7FFF FFFF，最小的负整数是0x8000 0000。\n",
    "\n",
    "inf表示无穷大，需要使用 float(‘inf’) 函数来转化，那么对应的就有\tfloat('-inf') 表示无穷小了。\n",
    "\n",
    "这样你就可以使用任意数来判断和它的关系了。\n",
    "\n",
    "那什么时候会出现inf呢？ 比如一个数字除以0，Python中会报错，但是numpy中会是一个inf或者-inf\n",
    "\n",
    "另外还有 nan，这种写法在 pandans 中常见，表示缺失的数据，所以一般用 nan 来表示。任何与其做运算结果都是 nan\n"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:49.548234Z",
     "start_time": "2025-01-16T15:13:49.544683Z"
    }
   },
   "source": [
    "import numpy as np\n",
    "\n",
    "#nan 是not a number的缩写，表示非数字，在numpy中表示一个非数字值，可以用来表示缺失数据\n",
    "# 创建一个nan和inf #\n",
    "a = np.nan\n",
    "b = np.inf\n",
    "print(a, type(a))\n",
    "print(b, type(b))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "nan <class 'float'>\n",
      "inf <class 'float'>\n"
     ]
    }
   ],
   "execution_count": 40
  },
  {
   "cell_type": "code",
   "source": [
    "# 并且 np.nan != np.nan\t结果是TRUE\n",
    "# 所以我们可以使用这两个结合使用判断nan的个数\n",
    "print(np.nan == np.nan)\n",
    "print(True == 1)\n",
    "print(False == 0)\n",
    "np.nan + 1  #nan和其他数运算的结果都是nan"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:50.244035Z",
     "start_time": "2025-01-16T15:13:50.240120Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n",
      "True\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "nan"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 41
  },
  {
   "cell_type": "code",
   "source": [
    "# --判断数组中为nan的个数\n",
    "t = np.arange(24, dtype=float).reshape(4, 6)\n",
    "\n",
    "# 将三行四列的数改成nan\n",
    "t[3, 4] = np.nan\n",
    "t[2, 4] = np.nan\n",
    "print(t)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:50.942565Z",
     "start_time": "2025-01-16T15:13:50.939919Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.  1.  2.  3.  4.  5.]\n",
      " [ 6.  7.  8.  9. 10. 11.]\n",
      " [12. 13. 14. 15. nan 17.]\n",
      " [18. 19. 20. 21. nan 23.]]\n"
     ]
    }
   ],
   "execution_count": 42
  },
  {
   "cell_type": "code",
   "source": [
    "# 可以使用np.count_nonzero() 来判断非零的个数\n",
    "# print(np.count_nonzero(t))\n",
    "print(t != t)\n",
    "print('-' * 50)\n",
    "print(np.count_nonzero(t != t))  # 统计nan的个数"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:53.227344Z",
     "start_time": "2025-01-16T15:13:53.223314Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[False False False False False False]\n",
      " [False False False False False False]\n",
      " [False False False False  True False]\n",
      " [False False False False  True False]]\n",
      "--------------------------------------------------\n",
      "2\n"
     ]
    }
   ],
   "execution_count": 43
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T15:13:57.258182Z",
     "start_time": "2025-01-16T15:13:57.254154Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 将nan替换为0\n",
    "t[np.isnan(t)] = 0\n",
    "print(t)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.  1.  2.  3.  4.  5.]\n",
      " [ 6.  7.  8.  9. 10. 11.]\n",
      " [12. 13. 14. 15.  0. 17.]\n",
      " [18. 19. 20. 21.  0. 23.]]\n"
     ]
    }
   ],
   "execution_count": 44
  },
  {
   "cell_type": "code",
   "source": [
    "# ----------练习： 处理数组中nan\n",
    "t = np.arange(24).reshape(4, 6).astype('float')\n",
    "#\n",
    "# 将数组中的一部分替换nan\n",
    "t[1, 3:] = np.nan\n",
    "print(t)\n",
    "print('-------------------')\n",
    "print(t.shape)\n",
    "print(id(t))\n",
    "print('-------------------')\n",
    "\n",
    "# 遍历每一列，然后判断每一列是否有nan\n",
    "for i in range(t.shape[1]):\n",
    "    #获取当前列数据\n",
    "    temp_col = t[:, i]\n",
    "\n",
    "    # 判断当前列的数据中是否含有nan\n",
    "    nan_num = np.count_nonzero(temp_col != temp_col)\n",
    "    # 条件成立说明含有nan\n",
    "    if nan_num != 0:\n",
    "        # 将这一列不为nan的数据拿出来,并计算平均值\n",
    "        temp_col_not_nan = temp_col[temp_col == temp_col]\n",
    "        print(temp_col_not_nan)\n",
    "        print('-' * 50)\n",
    "        # 将nan替换成这一列的平均值\n",
    "        temp_col[np.isnan(temp_col)] = np.mean(temp_col_not_nan)\n",
    "\n",
    "print(t)\n",
    "print(id(t))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T16:01:47.289685Z",
     "start_time": "2025-01-16T16:01:47.283739Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.  1.  2.  3.  4.  5.]\n",
      " [ 6.  7.  8. nan nan nan]\n",
      " [12. 13. 14. 15. 16. 17.]\n",
      " [18. 19. 20. 21. 22. 23.]]\n",
      "-------------------\n",
      "(4, 6)\n",
      "2436862794256\n",
      "-------------------\n",
      "[ 3. 15. 21.]\n",
      "--------------------------------------------------\n",
      "[ 4. 16. 22.]\n",
      "--------------------------------------------------\n",
      "[ 5. 17. 23.]\n",
      "--------------------------------------------------\n",
      "[[ 0.  1.  2.  3.  4.  5.]\n",
      " [ 6.  7.  8. 13. 14. 15.]\n",
      " [12. 13. 14. 15. 16. 17.]\n",
      " [18. 19. 20. 21. 22. 23.]]\n",
      "2436862794256\n"
     ]
    }
   ],
   "execution_count": 46
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T17:20:49.762303Z",
     "start_time": "2025-01-16T17:20:49.750418Z"
    }
   },
   "source": [
    "print(np.inf == np.inf)\n",
    "np.inf"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "inf"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 47
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T17:21:41.794102Z",
     "start_time": "2025-01-16T17:21:41.789936Z"
    }
   },
   "source": [
    "# np.nan和任何数据运算的结果都是nan\n",
    "t = np.arange(24).reshape(4, 6).astype('float')\n",
    "# 将数组中的一部分替换nan\n",
    "t[1, 3:] = np.nan\n",
    "\n",
    "t1 = np.arange(24).reshape(4, 6).astype('float')\n",
    "t + t1"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.,  2.,  4.,  6.,  8., 10.],\n",
       "       [12., 14., 16., nan, nan, nan],\n",
       "       [24., 26., 28., 30., 32., 34.],\n",
       "       [36., 38., 40., 42., 44., 46.]])"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 48
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T17:22:01.923466Z",
     "start_time": "2025-01-16T17:22:01.911915Z"
    }
   },
   "source": [
    "arr = np.array([-1, 0])\n",
    "print(arr)\n",
    "print(arr[0] / arr[1])  #1除0就会得到inf"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[-1  0]\n",
      "-inf\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Administrator\\AppData\\Local\\Temp\\ipykernel_28052\\773640058.py:3: RuntimeWarning: divide by zero encountered in scalar divide\n",
      "  print(arr[0] / arr[1])  #1除0就会得到inf\n"
     ]
    }
   ],
   "execution_count": 49
  },
  {
   "cell_type": "code",
   "source": "np.nan + np.inf",
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T17:22:02.950182Z",
     "start_time": "2025-01-16T17:22:02.946674Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "nan"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 50
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 转置和轴滚动"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-16T17:23:45.627422Z",
     "start_time": "2025-01-16T17:23:45.623243Z"
    }
   },
   "source": [
    "#对换数组的维度\n",
    "import numpy as np\n",
    "\n",
    "a = np.arange(12).reshape(3, 4)\n",
    "print('原数组：')\n",
    "print(a)\n",
    "print('\\n')\n",
    "\n",
    "print('转置数组：')\n",
    "print(np.transpose(a))\n",
    "print(a)\n",
    "\n",
    "# 与transpose一致\n",
    "a = np.arange(12).reshape(3, 4)\n",
    "\n",
    "print('原数组：')\n",
    "print(a)\n",
    "print('\\n')\n",
    "\n",
    "print('转置数组：')\n",
    "print(a.T)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "原数组：\n",
      "[[ 0  1  2  3]\n",
      " [ 4  5  6  7]\n",
      " [ 8  9 10 11]]\n",
      "\n",
      "\n",
      "转置数组：\n",
      "[[ 0  4  8]\n",
      " [ 1  5  9]\n",
      " [ 2  6 10]\n",
      " [ 3  7 11]]\n",
      "[[ 0  1  2  3]\n",
      " [ 4  5  6  7]\n",
      " [ 8  9 10 11]]\n",
      "原数组：\n",
      "[[ 0  1  2  3]\n",
      " [ 4  5  6  7]\n",
      " [ 8  9 10 11]]\n",
      "\n",
      "\n",
      "转置数组：\n",
      "[[ 0  4  8]\n",
      " [ 1  5  9]\n",
      " [ 2  6 10]\n",
      " [ 3  7 11]]\n"
     ]
    }
   ],
   "execution_count": 51
  },
  {
   "cell_type": "code",
   "source": [
    "# 函数用于交换数组的两个轴\n",
    "t1 = np.arange(24).reshape(4, 6)\n",
    "re1 = t1.swapaxes(1, 0)\n",
    "\n",
    "print(' 原 数 组 ：')\n",
    "print(t1)\n",
    "print('\\n')\n",
    "print(re1.shape)\n",
    "print('调用 swapaxes 函数后的数组：')\n",
    "print(re1)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T17:24:38.623879Z",
     "start_time": "2025-01-16T17:24:38.619254Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " 原 数 组 ：\n",
      "[[ 0  1  2  3  4  5]\n",
      " [ 6  7  8  9 10 11]\n",
      " [12 13 14 15 16 17]\n",
      " [18 19 20 21 22 23]]\n",
      "\n",
      "\n",
      "(6, 4)\n",
      "调用 swapaxes 函数后的数组：\n",
      "[[ 0  6 12 18]\n",
      " [ 1  7 13 19]\n",
      " [ 2  8 14 20]\n",
      " [ 3  9 15 21]\n",
      " [ 4 10 16 22]\n",
      " [ 5 11 17 23]]\n"
     ]
    }
   ],
   "execution_count": 52
  },
  {
   "cell_type": "code",
   "source": [
    "# 3维以上，称为轴交换\n",
    "t3 = np.arange(60).reshape(3, 4, 5)\n",
    "print(t3.shape)\n",
    "print('-' * 50)\n",
    "t3 = np.swapaxes(t3, 1, 2)\n",
    "print(t3.shape)\n",
    "# print(t3) 数据不用记住，不用观察"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-16T17:25:32.288558Z",
     "start_time": "2025-01-16T17:25:32.284861Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3, 4, 5)\n",
      "--------------------------------------------------\n",
      "(3, 5, 4)\n"
     ]
    }
   ],
   "execution_count": 53
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T03:05:52.238877Z",
     "start_time": "2025-01-17T03:05:52.235773Z"
    }
   },
   "source": [
    "# 数组的轴滚动,swapaxes每次只能交换两个轴，没有rollaxis方便，默认情况下轴滚动最前面\n",
    "import numpy as np\n",
    "\n",
    "a = np.ones((3, 4, 5, 6))\n",
    "# np.rollaxis(a, 2).shape\n",
    "b = np.rollaxis(a, 3, 1)\n",
    "b.shape  # 3轴放1轴之前"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(3, 6, 4, 5)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T03:10:29.339261Z",
     "start_time": "2025-01-17T03:10:29.336232Z"
    }
   },
   "cell_type": "code",
   "source": [
    "c = np.rollaxis(b, 1, 3)  # 尝试还原：1放3轴之前\n",
    "print(c.shape)\n",
    "np.rollaxis(b, 1, 4).shape  # 还原"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3, 4, 6, 5)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(3, 4, 5, 6)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 7
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T03:12:36.424341Z",
     "start_time": "2025-01-17T03:12:36.411114Z"
    }
   },
   "source": [
    "#数据拷贝，copy()和赋值的区别\n",
    "b = np.array([[1, 2, 3], [1, 2, 3]])\n",
    "a = b.copy()\n",
    "a"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1, 2, 3],\n",
       "       [1, 2, 3]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 8
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T03:12:43.881250Z",
     "start_time": "2025-01-17T03:12:43.878456Z"
    }
   },
   "source": [
    "b[0, 0] = 3\n",
    "print(b)\n",
    "a"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[3 2 3]\n",
      " [1 2 3]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[1, 2, 3],\n",
       "       [1, 2, 3]])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 9
  },
  {
   "cell_type": "code",
   "source": [
    "#随机数生成\n",
    "arr = np.random.rand(2, 3, 4)\n",
    "print(arr)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-17T03:13:05.211071Z",
     "start_time": "2025-01-17T03:13:05.167970Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[0.7738168  0.1686566  0.55199987 0.81897861]\n",
      "  [0.74815676 0.21694472 0.02912975 0.00649318]\n",
      "  [0.68890199 0.64045237 0.4934598  0.29648285]]\n",
      "\n",
      " [[0.29478937 0.17381883 0.00418664 0.03992344]\n",
      "  [0.46677828 0.78447887 0.82401567 0.5672317 ]\n",
      "  [0.74714754 0.53527741 0.46680036 0.29702508]]]\n"
     ]
    }
   ],
   "execution_count": 10
  },
  {
   "cell_type": "code",
   "source": [
    "names = 'zhangsan,lisi,wangwu,zhaoliu,sunqi'\n",
    "#写入文件\n",
    "with open('names.csv', 'w') as f:\n",
    "    f.write(names)\n",
    "    f.write('\\n')\n",
    "    f.write('12,23,34,45,56')\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-17T03:23:07.562399Z",
     "start_time": "2025-01-17T03:23:07.559514Z"
    }
   },
   "outputs": [],
   "execution_count": 11
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
